﻿using NET6.WebAPI.Extensions;
using NET6.WebAPI.Helpers;
using System.ComponentModel.DataAnnotations;

namespace NET6.WebAPI.Attributes
{
    /// <summary>
    /// 枚举验证属性
    /// </summary>
    public class EnumValidationAttribute : ValidationAttribute
    {
        private readonly Type _enumType;

        public EnumValidationAttribute(Type enumType)
        {
            _enumType = enumType;
        }

        protected override ValidationResult? IsValid(object? value, ValidationContext validationContext)
        {
            if (value == null) return ValidationResult.Success;

            if (!_enumType.IsEnum)
            {
                throw new InvalidOperationException($"{_enumType.Name} is not an Enum type.");
            }

            if (!Enum.IsDefined(_enumType, value))
            {
                var infos = EnumHelper.GetEnumInfos(_enumType);
                return new ValidationResult($"请输入有效的类型值，类型定义如下：{infos.ToJson()}");
            }

            return ValidationResult.Success;
        }
    }
}
